package com.kawins.mina.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.kawins.mina.net.HttpServerProtocolCodecFactory;

public class HttpServerContext {

	private Logger log = Logger.getLogger(getClass());
	private NioSocketAcceptor acceptor;

	private int getConfig() {
		Properties prop = new Properties();
		InputStream in = Object.class.getResourceAsStream("/mina.properties");
		try {
			prop.load(in);
			return Integer.parseInt(prop.getProperty("port").trim());
		} catch (Exception e) {
			log.error("Reading configuration port exceptions, use the default port:3005");
			return 3005;
		}
	}

	public void bind() {
		acceptor = new NioSocketAcceptor();
		acceptor.getFilterChain().addLast("protocolFilter",
				new ProtocolCodecFilter(new HttpServerProtocolCodecFactory()));
		acceptor.setHandler(new MinaIoHandler());
		int port = getConfig();
		try {
			acceptor.bind(new InetSocketAddress(port));
			log.info("Open port [" + port + "] success");
		} catch (IOException e) {
			log.error("Open port [" + port + "] failure");
			e.printStackTrace();
		}
	}

	public void unbind() {
		acceptor.unbind();
	}
}
